package com.etalk.crm.serviceImpl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.etalk.crm.dao.LessonIncompleteReasonMapper;
import com.etalk.crm.dao.LessonJoinVoidReasonMapper;
import com.etalk.crm.dao.LessonsMapper;
import com.etalk.crm.dao.PersonMapper;
import com.etalk.crm.dao.SSCNewMainMapper;
import com.etalk.crm.dao.StudentDynamicsMapper;
import com.etalk.crm.pojo.*;
import com.etalk.crm.service.SSCNewMainService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.TemporalAdjusters;
import java.util.*;

/**
 * @author James
 * @date 2018/12/28 18:33
 * @description ssc 首页面板列表
 */
@Service
public class SscNewMainServiceImpl implements SSCNewMainService {
    @Resource
    private SSCNewMainMapper sscNewMainMapper;

    @Resource
    private StudentDynamicsMapper studentDynamicsMapper;

    @Resource
    private PersonMapper personMapper;

    @Resource
    LessonsMapper lessonsMapper;

    @Resource
    LessonIncompleteReasonMapper lessonIncompleteReasonMapper;

    @Resource
    private LessonJoinVoidReasonMapper lessonJoinVoidReasonMapper;

    @Override
    public PageInfo<NewMainBean> selectMaterialFinishedBySSC(int sscId, Integer page, Integer size) {
        PageHelper.startPage(page, size);
        return new PageInfo<>(sscNewMainMapper.selectMaterialFinishedBySSC(sscId));
    }

    @Override
    public PageInfo<NewMainBean> selectOcNewStudent(int sscId, Integer page, Integer size) {
        PageHelper.startPage(page, size);
        return new PageInfo<>(sscNewMainMapper.selectOcNewStudent(sscId));
    }

    @Override
    public PageInfo<NewMainBean> selectLessonState(int sscId, Integer page, Integer size) {
        PageHelper.startPage(page, size);
        return new PageInfo<>(sscNewMainMapper.selectLessonState(sscId));
    }

    @Override
    public PageInfo<NewMainBean> selectInactiveLessons(int sscId, Integer page, Integer size) {
        PageHelper.startPage(page, size);
        return new PageInfo<>(sscNewMainMapper.selectInactiveLessons(sscId));
    }

    @Override
    public PageInfo<NewMainBean> selectTeacherRank(int sscId,String searchKeys, Integer page, Integer size) {
        PageHelper.startPage(page, size);
        List<String> listSearchKey=new ArrayList<>();
        if (StringUtils.isNotEmpty(searchKeys)){
            searchKeys=searchKeys.trim();
            listSearchKey.addAll(Arrays.asList(searchKeys.split(" ")));
        }
        return new PageInfo<>(sscNewMainMapper.selectTeacherRank(sscId,listSearchKey));
    }

    @Override
    public PageInfo<NewMainBean> renewOrders(int sscId, Integer page, Integer size) {
        PageHelper.startPage(page, size);
        return new PageInfo<>(sscNewMainMapper.renewOrders(sscId));
    }

    @Override
    public PageInfo<NewMainBean> leaveTeacherStu(int sscId, Integer page, Integer size) {
        PageHelper.startPage(page, size);
        return new PageInfo<>(sscNewMainMapper.selectLeaveTeacherStu(sscId));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int updateRenewOrdersfinish(String orderId) {
        return sscNewMainMapper.updateRenewOrdersfinish(orderId);
    }

    @Override
    public PageInfo<NewMainBean> searchFeedbackInfoByPage(int sscId, Integer page, Integer size) {
        PageHelper.startPage(page, size);
        return new PageInfo<>(sscNewMainMapper.searchFeedbackInfoByPage(sscId));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int addFeedbackResult(PersonFeedback feedback) {
        //添加一条动态
        PersonFeedback pf = sscNewMainMapper.selectByFeedbackId(feedback.getId());
        Person person = personMapper.selectByPersonId(feedback.getPersonId());
        pf.setFeedbackType("建议");
        pf.setFeedbackResult(feedback.getFeedbackResult());
        StudentDynamics sd = new StudentDynamics();
        sd.setAddTime(new Date());
        sd.setAddUser(feedback.getResultUser());
        sd.setPersonId(pf.getPersonId());
        sd.setStudentLogin(person.getLoginName());
        sd.setAddUserId(feedback.getPersonId());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        sd.setContent("【学生反馈】回复了" + person.getLoginName() + "在 " + sdf.format(pf.getAddTime()) + "提交的建议（" + pf.getFeedbackInfo()
                + ")," + "内容为：" + feedback.getFeedbackResult());
        int result = sscNewMainMapper.addFeedbackResultById(pf);
        if (result > 0) {
            return studentDynamicsMapper.addStuDynamic(sd);
        }
        return 0;
    }

    @Override
    public PageInfo<NewMainBean> selectOcOldStudent(int sscId,Integer followDays, Integer page, Integer size) {
        PageHelper.startPage(page, size);
        return new PageInfo<>(sscNewMainMapper.selectOcOldStudent(sscId,followDays));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int addTeacherRankReply(int lessonsId, String reply, String addUserName, int addUserId) {
        Lessons less = lessonsMapper.selectEvaluationReply(lessonsId);
        StudentDynamics sd = this.getStudentDynamics(less, addUserName, addUserId);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        sd.setContent("【老师投诉】上课时间：" + sdf.format(less.getReleaseTime()) + "  处理结果 :" + reply);
        //添加 老师投诉学员 回复
        int flag = sscNewMainMapper.updateLessonCommentByLessonId(reply, addUserName, lessonsId);
        if (flag > 0) {
            //添加动态
            return studentDynamicsMapper.addStuDynamic(sd);
        }
        return 0;
    }

    @Override
    public Lessons selectLessonInfoById(int lessonId) {
        return sscNewMainMapper.selectLessonInfoById(lessonId);
    }

    @Override
    public Map<String, Object> searcherVoidReasonList(int lessonId) {
        Map<String, Object> map = new HashMap<>();
        map.put("reasonList", sscNewMainMapper.selectVoidReasonList(lessonId));
        map.put("results", sscNewMainMapper.selectByPrimaryKey(lessonId));
        map.put("incomplet", lessonIncompleteReasonMapper.selectIncompleteReasonByLessonId(lessonId));
        return map;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int addVoidReason(JSONObject jsonObject, String addUserName, int addUserId) {
        int lessonId = jsonObject.getIntValue("lessonId");
        int flag = 0;
        lessonJoinVoidReasonMapper.deleteByLessonId(lessonId);
        int vstype = jsonObject.getIntValue("vstype");
        int state = jsonObject.getIntValue("state");
        //转换成  list
        JSONArray objectList = jsonObject.getJSONArray("reasonArray");
        List<LessonJoinVoidReason> reasonsList = new ArrayList<>();
        LessonJoinVoidReason resons;
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < objectList.size(); i++) {
            JSONObject object = objectList.getJSONObject(i);
            if (i == objectList.size() - 1) {
                sb.append(object.getString("result")).append("。");
            } else {
                sb.append(object.getString("result")).append(";");
            }
            resons = new LessonJoinVoidReason();
            resons.setVoidReasonId(object.getIntValue("voidReasonId"));
            resons.setResult(object.getString("result"));
            resons.setLessonId(lessonId);
            reasonsList.add(resons);
        }
        lessonJoinVoidReasonMapper.addVoidSeason(reasonsList, addUserName, lessonId);
        LessonJoinVoidReason lessonJoinVoidReason = new LessonJoinVoidReason();
        lessonJoinVoidReason.setResult("");
        lessonJoinVoidReason.setType(vstype);
        lessonJoinVoidReason.setState(state);
        lessonJoinVoidReason.setResult("");
        lessonJoinVoidReason.setLessonId(lessonId);
        if (lessonJoinVoidReasonMapper.selectVoidReasonByLessonId(lessonId) > 0) {
            lessonJoinVoidReason.setRecorder(addUserName);
            lessonJoinVoidReason.setAddUserName("");
            flag += lessonJoinVoidReasonMapper.updateByPrimaryKeySelective(lessonJoinVoidReason);
        } else {
            lessonJoinVoidReason.setAddUserName(addUserName);
            lessonJoinVoidReason.setRecorder("");
            flag += lessonJoinVoidReasonMapper.addVoidReason(lessonJoinVoidReason);
        }
        if (state == 1) {
            Lessons lessons = lessonsMapper.selectEvaluationReply(lessonId);
            StudentDynamics sd = this.getStudentDynamics(lessons, addUserName, addUserId);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            String content = (vstype == 1 ? "【投诉】" : "非投诉") + "调查课程(" + lessons.getId() + "),上课时间：" + sdf.format(lessons.getReleaseTime()) + ",老师：" + lessons.getTeacherLogin() + "，调查结果：" + sb.toString();
            sd.setContent(content);
            flag += studentDynamicsMapper.addStuDynamic(sd);
        }
        return flag;
    }

    /**
     * 设置动态添加数据对象(部分数据)
     *
     * @param lessons     Lessons数据对象
     * @param addUserName 添加人名称
     * @param addUserId   添加人id
     * @return 动态对象
     */
    private StudentDynamics getStudentDynamics(Lessons lessons, String addUserName, int addUserId) {
        StudentDynamics sd = new StudentDynamics();
        sd.setAddTime(new Date());
        sd.setAddUser(addUserName);
        sd.setQuestionnaireId(0);
        sd.setPersonId(lessons.getPersonId());
        sd.setStudentLogin(lessons.getStudentLogin());
        sd.setAddUserId(addUserId);
        return sd;
    }

    @Override
    public PageInfo<NewMainBean> ocInfo(int sscId, Integer page, Integer size) {
        PageHelper.startPage(page, size);
        return new PageInfo<>(sscNewMainMapper.selectOcInfo(sscId));
    }

    /**
     * 查询钻石学员跟进情况
     * @param sscId 学习顾问id
     * @param page 页码
     * @param size 页记录数
     * @return
     */
    @Override
    public PageInfo<NewMainBean> searchDiamondStudentFollowList(int sscId, Integer page, Integer size){
        PageHelper.startPage(page, size);
        return new PageInfo<>(sscNewMainMapper.selectDiamondStudentFollowList(sscId));
    }

    /**
     * 获取待批改试卷数据
     * @param sscId ssc id
     * @param page 页码
     * @param size 页记录数
     * @return
     */
    @Override
    public PageInfo<NewMainBean> searchCorrectedTestPaperList(int sscId, Integer page, Integer size){
        PageHelper.startPage(page, size);
        return new PageInfo<>(sscNewMainMapper.selectCorrectedTestPaperList(sscId));
    }

    /**
     * 查询完成阶段检测课后24小时后未约中教课的数据
     * @param sscId ssc id
     * @param page 页码
     * @param size 页记录
     * @return
     */
    @Override
    public PageInfo<NewMainBean> searchNotBookedChineseCourseList(int sscId,Integer revisitId, Integer page, Integer size){
        PageHelper.startPage(page, size);
        return new PageInfo<>(sscNewMainMapper.selectNotBookedChineseCourseList(sscId,revisitId));
    }

    /**
     * 查询阶段检测课没有提交检测报告学员
     * @param sscId ssc id
     * @param page 页码
     * @param size 页记录
     * @return
     */
    @Override
    public PageInfo<NewMainBean> searchLtNotFeedbackList(int sscId,Integer page, Integer size){
        PageHelper.startPage(page, size);
        return new PageInfo<>(sscNewMainMapper.selectLtNotFeedbackList(sscId));
    }

    /**
     * 获得自动约课失败记录
     * @param sscId cc id
     * @param page 页码
     * @param size 记录数
     * @return
     */
    @Override
    public PageInfo<NewMainBean> searchAutoBookedFailList(int sscId, Integer page, Integer size){
        PageHelper.startPage(page, size);
        List<NewMainBean> list=sscNewMainMapper.selectAutoBookedFailList(sscId);
        for (NewMainBean newMainBean:list){
            JSONObject obj= JSON.parseObject(newMainBean.getRemark());
            newMainBean.setRemark(obj.getString("msg"));
        }
        return new PageInfo<>(list);
    }

    /**
     * 修改记录处理状态
     * @param id 失败记录id
     * @return
     */
    @Override
    public int modifyAutoBookedFailState(int id){
        return sscNewMainMapper.updateAutoBookedFailStateById(id);
    }

    /**
     * 学员上课表现3星及以下列表
     * @param sscId ssc id
     * @param page 页码
     * @param size 记录数
     * @return
     */
    @Override
    public PageInfo<NewMainBean> searchClassAttitudeList(int sscId, Integer page, Integer size){
        PageHelper.startPage(page, size);
        List<NewMainBean> list=sscNewMainMapper.selectClassAttitudeList(sscId);

        return new PageInfo<>(list);
    }

    /**
     * 学员上周、本周、下周课程数少于3节记录
     * @param sscId ssc id
     * @param weekId 上周(-1),本周(0),下周(1)
     * @param ltId 学管师学员查询：1学管师，2非学管师
     * @param page 页码
     * @param size 记录数
     * @return
     */
    @Override
    public PageInfo<NewMainBean> searchWeekClassInfoList(int sscId,Integer weekId,Integer ltId, Integer page, Integer size){
        PageHelper.startPage(page, size);
        List<NewMainBean> list=sscNewMainMapper.selectWeekClassInfoList(sscId,weekId,ltId);

        return new PageInfo<>(list);
    }

    /**
     * 查询自动约课订单不能满足下一次自动约课的订单信息
     * @param sscId ssc id
     * @param page 页码
     * @param size 页记录
     * @return
     */
    @Override
    public PageInfo<SurplusAutoOrderMap> searchSurplusAutoOrderList(int sscId, Integer page, Integer size) {
        PageHelper.startPage(page, size);
        List<SurplusAutoOrderMap> list = sscNewMainMapper.selectSurplusAutoOrderList(sscId);
        /*LocalDate localDate=LocalDate.now().with(TemporalAdjusters.next(DayOfWeek.SUNDAY)).with(TemporalAdjusters.next(DayOfWeek.THURSDAY));
        for (SurplusAutoOrderMap record:list){
            record.setLastBookedDate(Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant()));
        }*/
        return new PageInfo<>(list);
    }

    /**
     * 查询cc名下学员最近两次成绩
     * @param sscId ssc id
     * @param page 页码
     * @param size 页记录数
     * @return
     */
    @Override
    public PageInfo<NewMainBean> searchLastTwoScoreList(int sscId, Integer page, Integer size){

        AchievementManagement record=sscNewMainMapper.selectNewScoreInfo();
        if (record==null){
            return new PageInfo<>();
        }
        PageHelper.startPage(page, size);
        List<NewMainBean> list=sscNewMainMapper.selectLastTwoScoreList(record.getIntYear(),record.getTerm(),record.getTestTime(),sscId);
        if (list!=null && list.size()>0){
            for (NewMainBean result:list){
                if (result.getScore2()!=null && result.getScore2().compareTo(BigDecimal.ZERO) > 0){
                    result.setDiffScore(result.getScore1().subtract(result.getScore2()));
                }
            }
            return new PageInfo<>(list);
        }
        return new PageInfo<>();
    }
}
